package me.zhengjie.wcs;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.NetConfig;
import me.zhengjie.domain.TaskResultService;
import me.zhengjie.dto.Request;
import me.zhengjie.dto.Response;
import me.zhengjie.dto.StorageReport;
import me.zhengjie.dto.sqlServer.*;
import me.zhengjie.repository.*;
import me.zhengjie.util.UniqueCodeUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class WmsToWcs {

    private final OutBoundMissionRepository outBoundMissionRepository;
    private final InBoundMissionRepository inBoundMissionRepository;
    private final OutBoundMissionHistoryRepository outBoundMissionHistoryRepository;
    private final InBoundMissionHistoryRepository inBoundMissionHistoryRepository;
    private final NetConfig netConfig;
    private final TaskResultService taskResultService;

    /**
     * 向wcs发送容器任务
     * @param wmsTask 容器任务
     * @return 响应结果
     */
    public Response sendTask(WmsTask wmsTask){
        // 拼接URL
        String WCS_URL = "http://" +
                netConfig.getWcsIp() +
                ":" +
                netConfig.getWcsPort() +
                netConfig.getTaskUrl();

        Request request = new Request();
        request.setMessageId(UniqueCodeUtil.createCode());
        request.setMessageTime(String.valueOf(new Date().getTime()));
        request.setMessageType("containerTask");
        request.setMessageDesc("容器任务下发");
        request.setData(wmsTask);
        try {

            ObjectMapper objectMapper = new ObjectMapper();
            // 将wcsRequest转为json格式
            String jsonBody = objectMapper.writeValueAsString(request);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
            // 将响应体转为wcsResponse
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(WCS_URL, requestEntity, String.class);
            String responseBody = responseEntity.getBody();

            if (wmsTask.getWcsTaskType()==1){

                // 创建任务状态
                saveTaskResult(wmsTask);
                // 存储到历史任务表中
                saveToMissionHistory(wmsTask,1);
                inBoundMissionRepository.deleteInBoundMissionByMissionCode(wmsTask.getWmsTaskId());
            }else if(wmsTask.getWcsTaskType()==2){

                // 创建任务状态
                saveTaskResult(wmsTask);
                // 存储到历史任务表中
                saveToMissionHistory(wmsTask,2);
            }
            return objectMapper.readValue(responseBody, Response.class);
        } catch (Exception e) {
            log.error("发送任务到wcs失败，失败原因：{}", e.toString());
            return null;
        }
    }

    /**
     * 向wcs发送储位信息
     *
     * @param storageList 储位信息
     */
    public void sendStorage(List<Storage> storageList){
        // 拼接URL
        String WCS_URL = "http://" +
                netConfig.getWcsIp() +
                ":" +
                netConfig.getWcsPort() +
                netConfig.getStorageUrl();
        log.info("同步储位接口：{}",WCS_URL);
        Request request = new Request();
        request.setMessageId(UniqueCodeUtil.createCode());
        request.setMessageTime(String.valueOf(new Date().getTime()));
        request.setMessageType("dicLocation");
        request.setMessageDesc("货位信息下发");

        List<StorageReport> storageReports = storageList.stream().map(x -> new StorageReport(x.getId(),x.getStorageCode(),x.getLogicalAddressType(),x.getZoneCode(),x.getAisle(),x.getLayer(),x.getRow(),x.getColumn(),x.getLocationInventoryStatus(),x.getStatus())).collect(Collectors.toList());

        request.setData(storageReports);
        ObjectMapper objectMapper = new ObjectMapper();
        try {

            // 将wcsRequest转为json格式
            String jsonBody = objectMapper.writeValueAsString(request);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
            // 将响应体转为wcsResponse
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.postForEntity(WCS_URL, requestEntity, String.class);
            /* ResponseEntity<String> responseEntity = restTemplate.postForEntity(WCS_URL, requestEntity, String.class);
            String responseBody = responseEntity.getBody();
            objectMapper.readValue(responseBody, Response.class);*/
        } catch (Exception e) {
            log.error("发送储位信息到wcs失败,失败原因:{}", e.toString());
        }
    }

    public void saveToMissionHistory(WmsTask wmsTask,int taskType){
        try {
            if (taskType == 1){
                InBoundMission inBoundMission = inBoundMissionRepository.findInBoundMissionByMissionCode(String.valueOf(wmsTask.getWmsTaskId()));
                InBoundMissionHistory inBoundMissionHistory = new InBoundMissionHistory();
                inBoundMissionHistory.setMissionCode(inBoundMission.getMissionCode());
                inBoundMissionHistory.setPalletCode(inBoundMission.getPalletCode());
                inBoundMissionHistory.setMissionStatus("任务执行中");
                inBoundMissionHistory.setSource(inBoundMission.getSource());
                inBoundMissionHistory.setDestination(inBoundMission.getDestination());
                inBoundMissionHistory.setCreateTime(inBoundMission.getCreateTime());
                inBoundMissionHistory.setStartTime(inBoundMission.getStartTime());
                inBoundMissionHistoryRepository.save(inBoundMissionHistory);
                log.info("保存入库历史任务成功");
            }else if (taskType == 2){
                OutBoundMission outBoundMission = outBoundMissionRepository.findOutBoundMissionByMissionCode(String.valueOf(wmsTask.getWmsTaskId()));
                OutBoundMissionHistory outBoundMissionHistory = new OutBoundMissionHistory();
                outBoundMissionHistory.setMissionCode(outBoundMission.getMissionCode());
                outBoundMissionHistory.setPalletCode(outBoundMission.getPalletCode());
                outBoundMissionHistory.setMissionStatus("任务执行中");
                outBoundMissionHistory.setSource(outBoundMission.getSource());
                outBoundMissionHistory.setDestination(outBoundMission.getDestination());
                outBoundMissionHistory.setCreateTime(outBoundMission.getCreateTime());
                outBoundMissionHistory.setStartTime(outBoundMission.getStartTime());
                outBoundMissionHistoryRepository.save(outBoundMissionHistory);
                log.info("保存出库历史任务成功");
            }
        } catch (Exception e) {

            log.error("保存历史任务失败：{}",e.toString());
        }
    }

    public void saveTaskResult(WmsTask wmsTask){
        TaskResult taskResult = new TaskResult();
        taskResult.setWmsTaskId(wmsTask.getWmsTaskId());
        taskResult.setWcsTaskType(wmsTask.getWcsTaskType());
        taskResult.setLpnCode(wmsTask.getLpnCode());
        taskResult.setFromLocation(wmsTask.getFromLocation());
        taskResult.setToLocation(wmsTask.getToLocation());
        taskResult.setCreated(LocalDateTime.now());
        taskResult.setStatus(0);
        taskResultService.saveTaskResult(taskResult);
    }
}
